package com.jiuyou.websocket.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiuyou.websocket.enums.RequestType;
import com.jiuyou.websocket.manager.WebSocketSessionManager;
import com.jiuyou.websocket.service.base.BaseService;
import com.jiuyou.websocket.util.DateTimeUtil;
import com.jiuyou.websocket.util.ResponseResult;
import com.ruoyi.chat.domain.ChatLast;
import com.ruoyi.chat.domain.ChatRecord;
import com.ruoyi.chat.service.IChatLastService;
import com.ruoyi.chat.service.IChatRecordService;
import com.ruoyi.chat.vo.ChatLastVO;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.domain.entity.StoreUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.member.service.IMemberService;
import com.ruoyi.store.domain.Store;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.store.service.IStoreService;
import com.ruoyi.store.service.IStoreUserRoleService;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;

import java.util.*;

/**
 * 消息处理service
 */

@Service
public class DisposeMessageService extends BaseService {

    private final Logger log = LoggerFactory.getLogger(DisposeMessageService.class);

    @Autowired
    private WebSocketSessionManager wsSessionManager;

    @Autowired
    private IChatRecordService chatRecordService;

    @Autowired
    private IChatLastService chatLastService;

    @Autowired
    private IMemberService memberService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IStoreUserRoleService roleService;
    /**
     * 获取我的未读消息数量
     * @return
     */
    public JSONObject getMyMsgUnreadCount(JSONObject jsonObjParam,WebSocketSession wsSession) {
        Long storeId = jsonObjParam.getLong("storeId");//门店id
        String platform=getPlatform(wsSession);
        ChatRecord chatRecordParam=new ChatRecord();
        chatRecordParam.setReadStatus("N");
        int unreadMsgCount =0;
        if("customer".equals(platform)){
            //C端用户查询未读消息
            Member member=(Member)getUser(wsSession);
            chatRecordParam.setMemberId(member.getId());
            chatRecordParam.setTostoreState("N");
        }
        if("store".equals(platform)){
            //B端用户查询未读消息
            StoreUser storeUser= (StoreUser)getUser(wsSession);
            StoreUserRole storeUserRole=getStoreUserRole(storeUser.getId(),storeId);
            if(null!=storeUserRole){
                chatRecordParam.setStoreId(storeUserRole.getStoreId());
                chatRecordParam.setTostoreState("Y");
            }else{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("unreadMsgCount", 0);
                jsonObject.put("msg", "无权限");
                return jsonObject;
            }

        }
        List<ChatRecord> list=chatRecordService.selectChatRecordList(chatRecordParam);
        unreadMsgCount = list.size();

       JSONObject jsonObject = new JSONObject();
        jsonObject.put("unreadMsgCount", unreadMsgCount);
        return jsonObject;
    }
    private StoreUserRole getStoreUserRole(Long storeUserId,Long storeId){
        List<StoreUserRole> storeUserRoles = roleService.selectStoreUserRoleByUserId(storeUserId, storeId,null);
        if(storeUserRoles.size()>0){
            return storeUserRoles.get(0);
        }else{
            return null;
        }

    }
    /**
     * 获取我的消息列表
     * @param jsonObjParam
     * @param wsSession
     * @return
     */
    public JSONObject getMyMsgList(JSONObject jsonObjParam, WebSocketSession wsSession) {
//        int page = jsonObjParam.getIntValue("page");
//        int rows = jsonObjParam.getIntValue("rows");
        int pageNum = jsonObjParam.getIntValue("pageNum");
        int pageSize = jsonObjParam.getIntValue("pageSize");
        Long storeId = jsonObjParam.getLong("storeId");//门店id
        Object user=getUser(wsSession);
        String platform=getPlatform(wsSession);
        ChatLast chatLastParam=new ChatLast();
        ChatRecord chatRecordParam=new ChatRecord();
        List<ChatLastVO> chatLastVOList=new ArrayList<ChatLastVO>();
        if("customer".equals(platform)){
            //用户消看到的息列表
            Member member=(Member)getUser(wsSession);
            chatLastParam.setMemberId(member.getId());
            chatRecordParam.setTostoreState("N");//
        }
        if("store".equals(platform)){
            //门店看到的消息列表
            StoreUser storeUser= (StoreUser)getUser(wsSession);
            StoreUserRole storeUserRole=getStoreUserRole(storeUser.getId(),storeId);
            if(null!=storeUserRole){
                chatLastParam.setStoreId(storeUserRole.getStoreId());
                chatRecordParam.setTostoreState("Y");//
            }else{
                JSONObject jsonInfo = new JSONObject();
                //jsonInfo.put("page", pageEntity);
                jsonInfo.put("data", chatLastVOList);
                jsonInfo.put("msg", "无权限");
                return jsonInfo;
            }



        }
        startPage(pageNum,pageSize,null);
        List<ChatLast>  chatLastList= chatLastService.selectChatLastList(chatLastParam);

        for (ChatLast chatLast:chatLastList) {
            ChatLastVO vo=new ChatLastVO();
            Long sId= chatLast.getStoreId();
            Long memberId=chatLast.getMemberId();
//            Store store= storeService.selectStoreById(sId);
            vo.setStoreImage(chatLast.getStoreHeadImg());
            vo.setStoreName(chatLast.getStoreNickName());
            vo.setStoreId(chatLast.getStoreId());
//            Member member=memberService.selectMemberById(memberId);
            vo.setMemberHeadImg(chatLast.getMemberHeadImg());
            vo.setMemberNickName(chatLast.getMemberNickName());
            vo.setMemberId(chatLast.getMemberId());
            String msgType= chatLast.getMsgType();
            vo.setMsgType(chatLast.getMsgType());
            vo.setContent(chatLast.getContent());
            if("img".equals(msgType)){
                vo.setContent("[图片]");
            }
            chatRecordParam.setStoreId(sId);
            chatRecordParam.setMemberId(memberId);
            chatRecordParam.setReadStatus("N");
            if(DicConstants.SYS_Y.getCode().equals(chatRecordParam.getTostoreState())){
                //门店看到的消息
                vo.setUnreadMsgCount(chatLast.getStoreUnread().intValue());
            }else{
                //用户消看到的息列表
                vo.setUnreadMsgCount(chatLast.getMemberUnread().intValue());
            }
            String todayDateStr = DateTimeUtil.getTodayDateStr();
            Date sendDate = chatLast.getCreateTime();
            String sendDateStr = DateTimeUtil.toDateString(new DateTime(sendDate));
            if(todayDateStr.equals(sendDateStr)){
                sendDateStr = DateTimeUtil.toTimeString(new DateTime(sendDate));
            } else {
                sendDateStr = new DateTime(sendDate).toString("MM-dd");
            }
            vo.setSendDateStr(sendDateStr);

            chatLastVOList.add(vo);
        }
        JSONObject jsonInfo = new JSONObject();
       //jsonInfo.put("page", pageEntity);
        jsonInfo.put("data", chatLastVOList);
        return jsonInfo;
    }

    /**
     * 获取与某人的对话列表倒序分页
     * @param jsonObjParam
     * @param wsSession
     * @return
     */
    public JSONObject getDialogByList(JSONObject jsonObjParam, WebSocketSession wsSession) {
        Object user = getUser(wsSession);//getMember(wsSession);
        int pageNum = jsonObjParam.getIntValue("pageNum");
        int pageSize = jsonObjParam.getIntValue("pageSize");
        //Long oppositeId = jsonObjParam.getLong("oppositeId");
        Long csId = jsonObjParam.getLong("csId");
        Long storeId = jsonObjParam.getLong("storeId");//门店id
        Long memberId = jsonObjParam.getLong("memberId");//用户ID
        String platform=getPlatform(wsSession);

        //分页查询列表
       // PageEntity pageEntity = new PageEntity(page, rows);
//        PageData<ChatRecord> pageData = chatRecordService.selectListByUserIdOr(memberId, oppositeId, csId, pageEntity);
//        //对方的信息
//        Member opposite = memberService.selectMemberById(oppositeId);
        ChatRecord chatRecordParam=new ChatRecord();
        chatRecordParam.setMemberId(memberId);
        chatRecordParam.setStoreId(storeId);
        chatRecordParam.setCsId(csId);
        startPage(pageNum,pageSize,null);
        List<ChatRecord>  chatRecordList=chatRecordService.selectChatRecordList(chatRecordParam);
        //long total=new PageInfo(chatRecordList).getTotal();
        TableDataInfo tableDataInfo =getDataTable(chatRecordList);
        String otherNickName="";
        String otherHeadImg="";
        if("customer".equals(platform)){
            Store store= storeService.selectStoreById(storeId);
            otherNickName=store.getStoreName();
            otherHeadImg=store.getStoreImage();
        }
        if("store".equals(platform)){

            Member member=memberService.selectMemberById(memberId);
            otherNickName=member.getNickName();
            otherHeadImg=member.getHeadImg();
        }
        JSONObject jsonObject = new JSONObject();//(JSONObject) JSON.toJSON(pageData);
        //jsonObject.put("memberHeadImg", member.getHeadImg());
        jsonObject.put("otherNickName", otherNickName);
        jsonObject.put("otherHeadImg", otherHeadImg);
        jsonObject.put("tableDataInfo",tableDataInfo);

        return jsonObject;
    }

    /**
     * 将某人发给我的信息变为已读
     * @param jsonObjParam
     * @param wsSession
     * @return
     */
    public JSONObject updateReadStatus(JSONObject jsonObjParam, WebSocketSession wsSession) {
        Long storeId = jsonObjParam.getLong("storeId");//门店id
        Long memberId= jsonObjParam.getLong("memberId");
        String tostoreState="";
        String platform=getPlatform(wsSession);
        if("customer".equals(platform)){
            //客户已读
            Member member=(Member)getUser(wsSession);
            memberId=member.getId();
            tostoreState="N";
        }
        if("store".equals(platform)){
            //门店已读
            tostoreState="Y";

        }
        chatRecordService.updateReadStatus(storeId,memberId,tostoreState);
        ChatLast chatLasParam=new ChatLast();
        chatLasParam.setMemberId(memberId);
        chatLasParam.setStoreId(storeId);
        List<ChatLast> listLast= chatLastService.selectChatLastList(chatLasParam);
        if(null!=listLast&&listLast.size()>0){
            ChatLast last=listLast.get(0);
            ChatLast lastU=new ChatLast();
            lastU.setId(last.getId());
            if(DicConstants.SYS_Y.getCode().equals(tostoreState)){
                lastU.setStoreUnread(0L);
            }else{
                lastU.setMemberUnread(0L);
            }
            chatLastService.updateChatLast(lastU);
        }

        return ResponseResult.toJSONObjectSuccess(new JSONObject());
    }

    /**
     * 给某人发消息
     * @param jsonObjParam
     * @param wsSession
     * @return
     */
    public JSONObject sendMsg(JSONObject jsonObjParam, WebSocketSession wsSession) {

      String content = jsonObjParam.getString("content");//发送内容
      String msgType = jsonObjParam.getString("msgType");//消息类型
      Long storeId = jsonObjParam.getLong("storeId");//门店id
      Long receiveId = jsonObjParam.getLong("receiveId");//接收人id
       DateTime dateTime = new DateTime();
        String platform=getPlatform(wsSession);
        ChatRecord chatRecord=new ChatRecord();
        chatRecord.setStoreId(storeId);//这个必须传过来，后期门店用户可能所属多个门店
        chatRecord.setMsgType(msgType);
        chatRecord.setContent(content);
        String userKey=null;
        ChatLast chatLasParam=new ChatLast();
        chatLasParam.setStoreId(storeId);
        if(null==storeId){
            return new JSONObject();
        }

        if("customer".equals(platform)){
            //发给门店
            //根据门店id获取店长id
            Long storeUserId=0L;
            StoreUserRole storeUserRolePara=new StoreUserRole();
            storeUserRolePara.setStoreId(storeId);
            List<StoreUserRole>  listStoreUserRole=roleService.selectStoreUserRoleList(storeUserRolePara);
            for (StoreUserRole su:listStoreUserRole) {
                if(DicConstants.STORE_Identity_Manager.getCode().equals(su.getRoleType())){
                    storeUserId=su.getStoreUserId();
                    break;
                }
            }

//            chatRecord.setStoreUserId(receiveId);
//            if(null!=receiveId){
//                chatRecord.setStoreUserName();
//            }
            Member member=(Member)getUser(wsSession);
            chatRecord.setMemberId(member.getId());
            chatRecord.setTostoreState("Y");
            chatLasParam.setMemberId(member.getId());
            userKey="store_"+storeUserId;
        }
        if("store".equals(platform)){
            //发给用户
            //StoreUser  storeUser=(StoreUser)getUser(wsSession);
            chatRecord.setMemberId(receiveId);
            chatLasParam.setMemberId(receiveId);
            chatRecord.setTostoreState("N");
            userKey="customer_"+receiveId;//platform+"_"+"27";
        }


        List<ChatLast>  listChatLast=  chatLastService.selectChatLastList(chatLasParam);
        ChatLast last=null;
        if(null==listChatLast||listChatLast.size()==0){
             last=new ChatLast();
            last.setContent(content);
            last.setStoreId(storeId);
            last.setMemberId(chatLasParam.getMemberId());
            last.setMsgType(msgType);
            if(DicConstants.SYS_Y.getCode().equals(chatRecord.getTostoreState())){
                //发送给门店
                last.setStoreUnread(1L);
            }else{
                //发送给用户
                last.setMemberUnread(1L);
            }
            chatLastService.insertChatLast(last);
        }else{
            last=listChatLast.get(0);
            last.setContent(content);
            last.setMsgType(msgType);
            last.setCreateTime(new Date());
            if(DicConstants.SYS_Y.getCode().equals(chatRecord.getTostoreState())){
                //发送给门店
                last.setStoreUnread(last.getStoreUnread()+1L);
            }else{
                //发送给用户
                last.setMemberUnread(last.getMemberUnread()+1L);
            }
            chatLastService.updateChatLast(last);
        }

        chatRecordService.insertChatRecord(chatRecord);
        //发送消息
        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("memberId", memberId);
//        jsonObject.put("nickName", nickName);
        jsonObject.put("content",content );
        jsonObject.put("sendTime", DateTimeUtil.toDateTimeString(dateTime));
        jsonObject.put("msgType",msgType);

        wsSessionManager.sendForward(userKey, RequestType.RECEIVE_MSG_INFORM, jsonObject,last);
//        Long storeId= chatLasParam.getStoreId();
        Long memberId=chatLasParam.getMemberId();
        Member member=memberService.selectMemberById(memberId);
        boolean needUp=false;
        ChatLast chatLastU=new ChatLast();
        chatLastU.setId(last.getId());
        if(StringUtils.isEmpty(last.getMemberNickName())||StringUtils.isEmpty(last.getMemberHeadImg())
                ||!last.getMemberNickName().equals(member.getNickName())||!last.getMemberHeadImg().equals(member.getHeadImg())
        ){ //需要更新
            needUp=true;
            chatLastU.setMemberHeadImg(member.getHeadImg());
            chatLastU.setMemberNickName(member.getNickName());
        }
        Store store=storeService.selectStoreById(storeId);
        if(StringUtils.isEmpty(last.getStoreNickName())||StringUtils.isEmpty(last.getStoreHeadImg())
                ||!last.getStoreNickName().equals(store.getStoreName())||!last.getStoreHeadImg().equals(store.getStoreImage())
        ){ //需要更新
            needUp=true;
            chatLastU.setStoreHeadImg(store.getStoreImage());
            chatLastU.setStoreNickName(store.getStoreName());
        }
        if(needUp){
            chatLastService.updateChatLast(chatLastU);
        }
        return null;
    }

    private void startPage(int pageNum,int pageSize,String orderBy)
    {
//        PageDomain pageDomain = TableSupport.buildPageRequest();
//        Integer pageNum = pageDomain.getPageNum();
//        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
           // String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            Boolean reasonable = true;
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
    }
    private TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        PageInfo pageInfo= new PageInfo(list);
        long total=pageInfo.getTotal();
        rspData.setTotal(total);
        rspData.setPages(pageInfo.getPages());
        rspData.setLastPage(pageInfo.isIsLastPage());
        return rspData;
    }
}
